<?php
namespace Home\Controller;

use Common\Utils\Constants;
use Home\Logic\CheckInLogLogic;
use Home\Logic\MatchLogLogic;
use Home\Logic\RaceLogic;
use Home\Logic\RoomLogic;
use Home\Logic\UserLogic;
use Think\Controller;

/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2017/8/22
 * Time: 14:58
 */

use Aliyun\Core\Config;
use Aliyun\Core\Profile\DefaultProfile;
use Aliyun\Core\DefaultAcsClient;
use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest;

class IndexController extends BaseController
{
    private static $_validate = array(
        array('game_name', 'require', '请填写游戏昵称！', 1, 'regex', 3),
        array('wechat_number', 'require', '请填写微信号！', 1, 'regex', 3),
//        array('qq_number', 'require', '请填写QQ号！', 1, 'regex', 3),
        array('region_name', 'require', '请选择地区！', 1, 'regex', 3),
        array('systems_name', 'require', '请选择手机系统！', 1, 'regex', 3),
        array('region', 'require', '请选择游戏战区！', 1, 'regex', 3),
        array('level', 'require', '请选择段位信息！', 1, 'regex', 3),
        array('phone', 'require', '请填写手机号！', 1, 'regex', 3),
        array('code', 'require', '请填写验证码！', 1, 'regex', 3),
    );

    public function index(){
        $user = $this->getUser();
        if(empty($user['phone'])){
            $this->redirect('/Home/Index/settings');
            return;
        }
        $is_show_integral = I('is_show_integral','0');
        if($is_show_integral == 0 && $user['is_first'] == 1) {
            $this->redirect('/Home/Index/slider');
            return;
        }
        $this->assign('head_url',$user['head_url']);
        $this->assign('level',$user['level']);
        $this->assign('is_first',$user['is_first']);
        $this->assign('is_check_in',$this->isCheckIn() ? 1 : 0);
        $this->assign('scrollImageList',$this->getScrollImageList());
        $this->assign('noticeList',$this->getNoticeList());
        $this->display();
    }

    public function index_new(){
        $user = $this->getUser();
        if(empty($user['phone'])){
            $this->redirect('/Home/Index/settings');
            return;
        }
        $is_show_integral = I('is_show_integral','0');
        if($is_show_integral == 0 && $user['is_first'] == 1) {
            $this->redirect('/Home/Index/slider');
            return;
        }
        $this->assign('head_url',$user['head_url']);
        $this->assign('is_first',$user['is_first']);
        $this->assign('is_check_in',$this->isCheckIn() ? 1 : 0);
        $this->assign('scrollImageList',$this->getScrollImageList());
        $this->assign('noticeList',$this->getNoticeList());
        $this->display('index1');
    }

    public function rank_new(){
        $this->display();
    }

    /**
     * 跳转到设置界面
     */
    public function settings(){
        $user = $this->getUser();
        $this->assign('user',$user);
        if(empty($user['phone'])){
            $config = D('Config')->where(array('name'=>Constants::CONFIG_REGISTER_REWARD_INTEGRAL))->find();
            $money = $config['value'];
            if(!is_numeric($money) || $money < 0) {//奖励钻石
                $money = 0;
            }
            $this->assign('integral',$money);
        }
        $this->display();
    }

    /**
     * 跳转到引导页
     */
    public function slider(){
        $this->display();
    }

    /**
     * 显示用户胜率排行
     */
    public function rank(){
//        $userList = D('User')->field('nickname,head_url,id,total_number,win_number,win_number/total_number as percentage')
//            ->where(array('total_number'=>array('EGT',10)))
//            ->order('percentage desc')->limit(1,10)->select();
//        foreach ($userList as $key => $value){
//            $userList[$key]['percentage'] = round($value['percentage'] * 100);
//        }
//        $this->assign('list',$userList);
        $config = D('Config')->where(array('name'=>Constants::CONFIG_SCREENINGS))->find();
        $screenings = $config['value'];
        if(empty($screenings) || !is_numeric($screenings)){
            $screenings = 10;
        }
        $this->assign('screenings',$screenings);
        $this->display('rank_new');
    }

    public function gameShow(){
        $config = D('Config')->where(array('name'=>Constants::CONFIG_GAME_SHOWS))->find();
        $content = html_entity_decode($config['value']);
        $this->assign('content',$content);
        $this->display('game_show');
    }

    //获取房间列表
    public function ajaxRoomList(){
        $logic = new RoomLogic();
        $user = $this->getUser();
//        $map['t_room.status'] = Constants::ROOM_STATUS_WAIT;
        $where['_string'] = ' t_room.status = '.Constants::ROOM_STATUS_PROCESSING.' OR'.' t_room.status = '.Constants::ROOM_STATUS_WAIT;
        $map['_complex'] = $where;
        $data = $logic->getRoomList($map,1,5,$user['id']);
        $this->assign('data',$data);
        $this->display('Room/ajaxRoomList');
    }

    //获取赛事列表
    public function ajaxRaceList(){
        $logic = new RaceLogic();
        $data = $logic->getRaceList(null,1,3);
        $this->assign('data',$data);
        $this->display('Race/ajaxRaceList');
    }

    /**
     * ajax签到
     */
    public function ajaxCheckIn(){
        $user = $this->getUser();
        $logic = new CheckInLogLogic();
        $result = $logic->checkIn($user['id']);
        $success = false;
        switch ($result['status']){
            case 0:
                $message = '对不起，您今天已经签到过了！';
                break;
            case 1:
                $success = true;
                $message = '签到成功！获得'.$result['money'].'金币奖励';
                break;
            case 2:
                $message = '签到失败，服务器繁忙！';
                break;
        }
        $this->ajax($success,$message);
    }

    /**
     * 设置用户信息
     */
    public function ajaxSetUserInfo(){
        $model = D('User');
        $phone = I('phone');
        $code = I('code');
        $data = $model->validate(self::$_validate)->create(I('post.'), 1);
        if (!$data) {
            $this->ajax(false,$model->getError());
        }
//        if(!isMobile($phone)){
//            $this->ajax(false,'请填写正确的手机号！');
//        }
        $sessionCode = session('code');
        $sessionPhone = session('number');
        if($code != $sessionCode){
            $this->ajax(false,'验证码不正确！');
        }
        if($phone != $sessionPhone){
            $this->ajax(false,'该手机号未验证！');
        }
        $user = $this->getUser();
        if(!empty($user['level'])){
            if($data['level'] < $user['level']){
                $this->ajax(false,'对不起，无法选择较低的段位，请联系客服修改。');
            }
        }
        $data['id'] = $user['id'];
        $logic = new UserLogic();
        $result = $logic->modifyUserInfo($data);
        $success = false;
        if($result == 0){
            $message = '修改资料失败！';
        }else{
            session('number','');
            session('code','');
            $success = true;
            $message = '修改资料成功！';
        }
        $data = array('is_first',$user['is_first']);
        $this->ajax($success,$message,-1,$data);
    }

    /**
     * ajax获取短信验证码
     */
    public function getCode(){
        $phone = I('phone');
        if(empty($phone) || !is_numeric($phone)){
            $this->ajax(false,'手机号输入有误，请重新输入！');
        }
        $create_time = session('create_time');
        $time = C('SMS_TIME');
        if (!empty($create_time) && time() - $create_time < $time) {
            $this->ajax(false,'不能重复获取！');
        }
        require_once  './Api/dysms/vendor/autoload.php';    //此处为你放置API的路径
        Config::load();             //加载区域结点配置
        $user = $this->getUser();
        if(empty($user['phone'])){
            $templateCode = Constants::SMS_TEMPLATE_REGISTER;
        }else{
            $templateCode = Constants::SMS_TEMPLATE_MODIFY;
        }
        if(!$this->isTestUser($user['openid'])) {
            $count = D('User')->where(array('phone' => $phone))->count();
            if ($user['phone'] != $phone && $count >= 1) {
                $this->ajax(false, '该手机号已经绑定过了！');
            }
        }
        $accessKeyId = C('APP_KEY');//参考本文档步骤2
        $accessKeySecret =  C('APP_SECRET');//参考本文档步骤2
        //短信API产品名（短信产品名固定，无需修改）
        $product = "Dysmsapi";
        //短信API产品域名（接口地址固定，无需修改）
        $domain = "dysmsapi.aliyuncs.com";
        //暂时不支持多Region（目前仅支持cn-hangzhou请勿修改）
        $region = "cn-hangzhou";
        //初始化访问的acsCleint
        $profile = DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret);
        DefaultProfile::addEndpoint("cn-hangzhou", "cn-hangzhou", $product, $domain);
        $acsClient= new DefaultAcsClient($profile);
        $request = new SendSmsRequest;
        //必填-短信接收号码。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
        $request->setPhoneNumbers($phone);
        //必填-短信签名
        $request->setSignName(C('SIGN_NAME'));
        //必填-短信模板Code
        $request->setTemplateCode($templateCode);
        //选填-假如模板中存在变量需要替换则为必填(JSON格式),友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
        $code = rand(100000, 999999);
        $request->setTemplateParam("{\"code\":\"".$code."\"}");
        //选填-发送短信流水号
        $request->setOutId(build_order_no());
        //发起访问请求
        $acsResponse = $acsClient->getAcsResponse($request);
        $result = json_decode(json_encode($acsResponse), true);
        if($result['Code'] == 'OK'){
            session('number',$phone);
            session('code',$code);
            $this->ajax(true,'已经发送成功！');
        }else{
            $this->ajax(false,'发送失败！',-1,$result);
        }
    }

    private function isTestUser($openid){
        foreach (Constants::TEST_USER_ARRAY as $key=>$value){
            if($value == $openid){
                return true;
            }
        }
        return false;
    }

    /**
     * 领取奖励
     */
    public function awardIntegral(){
        $user = $this->getUser();
        if($user['is_first'] == 0){
            $this->ajax(false,'对不起，您已经领取过奖励了，请到个人中心查看！');
        }
        $logic = new UserLogic();
        $status = $logic->rewardIntegralByRegister($user['id']);
        if($status == 1){
            $this->ajax(true,'领取成功！');
        }else{
            $this->ajax(false,'领取失败！'.$status);
        }

    }

    /**
     * 获取胜率榜 N场或以上
     */
    public function ajaxWinningList(){
        $config = D('Config')->where(array('name'=>Constants::CONFIG_SCREENINGS))->find();
        $number = $config['value'];
        if(empty($number) || !is_numeric($number)){
            $number = 10;
        }
        $userList = D('User')->field('nickname,head_url,id,total_number,win_number,win_number/total_number as percentage')
            ->where(array('total_number'=>array('EGT',$number)))
            ->order('percentage desc')->limit(0,30)->select();
        foreach ($userList as $key => $value){
            $userList[$key]['percentage'] = round($value['percentage'] * 100);
        }
        $this->assign('list',$userList);
        $this->display();
    }

    /**
     * 获取胜率榜 N场或以上 根据1v1 3v3 5v5
     */
    public function ajaxRankingList(){
        $config = D('Config')->where(array('name'=>Constants::CONFIG_SCREENINGS))->find();
        $number = $config['value'];
        if(empty($number) || !is_numeric($number)){
            $number = 10;
        }
        $type = I('type');
        $userList = D('Ranking')
            ->join('LEFT JOIN t_user u ON u.id=t_ranking.user_id')
            ->field('u.nickname,u.head_url,u.id,t_ranking.total_number,t_ranking.win_number,t_ranking.win_number/t_ranking.total_number as percentage')
            ->where(array('t_ranking.total_number'=>array('EGT',$number),'t_ranking.type'=>$type))
            ->order('percentage desc')->limit(0,30)->select();
        foreach ($userList as $key => $value){
            $userList[$key]['percentage'] = round($value['percentage'] * 100);
        }
        $this->assign('list',$userList);
        $this->display('ajaxWinningList');
    }

//    /**
//     * 对战次数榜
//     */
//    public function ajaxBattleTimesList(){
//        $userList = D('User')->field('nickname,head_url,id,total_number')
//            ->order('total_number desc')->limit(0,10)->select();
//        $this->assign('list',$userList);
//        $this->display();
//    }
    /**
     * 对战次数榜 通过类型
     */
    public function ajaxBattleTimesList(){
        $type = I('type');
        $battle_times  = D('Config')->where(array('name'=>Constants::CONFIG_BATTLE_TIMES))->find();
        $battle_times = $battle_times['value'];
        if(empty($battle_times) || !is_numeric($battle_times) || $battle_times <=0) {
            $battle_times = 4;
        }
        $userList = D('Ranking')
            ->join('LEFT JOIN t_user u ON u.id=t_ranking.user_id')
            ->field('u.nickname,u.head_url,u.id,t_ranking.total_number,t_ranking.win_number')
            ->where(array('t_ranking.total_number'=>array('EGT',$battle_times),'t_ranking.type'=>$type))
            ->order('t_ranking.total_number desc,u.id asc')->limit(0,10)->select();
        $this->assign('list',$userList);
        $this->display();
    }

    /**
     * 对战获得最多钻石榜
     */
    public function ajaxWinIntegralList(){
        $list = $this->sortMoneyLog(Constants::MONEY_TYPE_INTEGRAL,Constants::MONEY_SOURCE_WIN);
        $this->assign('list',$list);
        $this->display();
    }

    /**
     * 对战获得最多金币榜
     */
    public function ajaxWinGoldList(){
        $list = $this->sortMoneyLog(Constants::MONEY_TYPE_GOLD,Constants::MONEY_SOURCE_WIN);
        $this->assign('list',$list);
        $this->display();
    }

    private function sortMoneyLog($money_type,$type){
        $list = D('MoneyLog')
            ->join('LEFT JOIN t_user u ON u.id=t_money_log.user_id')
            ->where(array('money_type'=>$money_type,'type'=>$type))
            ->field('sum(t_money_log.money) as total_money ,u.nickname,u.head_url,u.total_number')
            ->order('total_money desc')
            ->group('t_money_log.user_id')
            ->limit(0,10)
            ->select();
        return $list;
    }


    //获取首页滚动图列表
    private function getScrollImageList(){
        $list = D('ScrollImage')->where(array('is_show' => 1))->select();
        return $list;
    }

    /**
     * 判断用户是否签到
     */
    private function isCheckIn(){
        $logic = new CheckInLogLogic();
        $user = $this->getUser();
        return $logic->isCheckIn($user['id']);
    }

    //获取公告列表
    private function getNoticeList(){
        $logic = new MatchLogLogic();
        $noticeList = $logic->getMatchLogListByNotice(1,10);
        return $noticeList;
    }



}